<template>
  
    <ProTable :columns="columns" :request="(params) => getServiceOrders({ ...params , condition:{...params, startDate: params.startDate? params.startDate[0]||'' : '', endDate:params.startDate? params.startDate[1]||'' : ''}})"  :action-ref="setActionRef" 
      :search="{ collapsed:false }"
      header-title=""
      :defaultFormData="{startDate:'',endDate:''}"
      :scroll="{ x: 8400 }">
      <template #action="{ record }">
        <!-- <a-button  type="text" @click="messageStatus(record)">短信状态</a-button> -->
        <a-button v-auth="'detailOrderBtn'" type="text" @click="showDetail(record)">查看</a-button>
        <a-button v-auth="'addOrderServiceBtn'" type="text" @click="handleAdd(record)">增加服务</a-button>
        <a-button v-auth="'changeInfoBtn'" type="text" @click="showEditForm(record)">更改信息</a-button>
      
        <!-- <a-button type="text" @click="handleEdit(record)">修改服务</a-button> -->
        <a-button type="text"  @click="showRefundForm(record)" :disabled="record.returnStatus">发起退款</a-button>
        <a-popconfirm content="确认发起退款么"  @ok="cancel(record)">
         <a-button v-auth="'cancelOrderBtn'" type="text" :disabled="record.returnStatus">取消订单</a-button>
        </a-popconfirm>
        

        <!-- <a-button type="text" status="danger" @click="confirmDelete(record)">删除</a-button> -->
      </template>
      <template #option-render="{ dom ,form}">
        <!-- <a-button type="primary" @click="showAddForm">添加服务订单</a-button> -->
          <a-button v-auth="'exportServiceOrderBtn'" type="primary" @click="exportHandle(form)">导出</a-button>
          <component :is="dom[1]" />
          <component :is="dom[0]" />
        </template>
    </ProTable>
  
    <ServiceOrderForm v-if="isFormVisible" :order="selectedOrder" @submit="handleSubmit" @cancel="hideForm" />
    <ServiceOrderDetail v-if="isDetailVisible" :order="selectedOrder" @close="hideDetail" />
    <a-modal v-model:visible="isRefundFormVisible" title="发起退款" @ok="handleRefundSubmit" @cancel="hideRefundForm">
      <a-form :model="refundForm">
        <a-form-item label="退款金额">
          <a-input-number  v-model="refundForm.returnPrice" />
        </a-form-item>
        <a-form-item label="退款原因">
          <a-textarea :row="4" v-model="refundForm.returnRemark" />
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal v-model:visible="isAddFormVisible" title="添加服务订单" @ok="handleAddSubmit" :width="1400" >
      <ServiceReservation v-model="serviceReservationData" :productType="productType"  :chargeType="chargeType" />
      <a-form-item label="需求记录" style="margin-top: 20px;">
        <a-textarea :rows="4" v-model="serviceData.requirementRecord" placeholder="需求记录" />
       </a-form-item>

        <!-- 上传需求记录 -->
        <a-form-item label="上传需求附件">
          <UploadFile v-model="serviceData.fileList"></UploadFile>
        </a-form-item>
        <a-form-item label="预约日期" field="reservationTime">
                <a-date-picker show-time v-model="serviceData.reservationTime" format="YYYY-MM-DD HH:mm" :disabledDate="(current) => dayjs(current).isBefore(dayjs().add(-1, 'day'))" />
              </a-form-item>
    </a-modal>

    <a-modal v-model:visible="isSmsStatusVisible" title="短信状态" :width="800" >
      <ProTable  :columns="smsStatusColumns" :action-ref="setActionRefm" :request="(params) => getSmsStatusList(selectedOrder.id)"  :search="false"
      header-title="">
      </ProTable>
    </a-modal>
  </template>
  
  <script lang="ts">
  import { defineComponent, ref, onMounted } from 'vue';
  import ServiceOrderForm from './ServiceOrderForm.vue';
  import ServiceOrderDetail from './ServiceOrderDetail.vue';
  import { getServiceOrders, deleteServiceOrder, addServiceOrder,getServiceOrderDetail,getProductDetail,getSmsStatusList } from '@/api/serviceOrder';
  import { createRefund } from '@/api/refund'; 
  import { Modal, Form, Input, Button, Message } from '@arco-design/web-vue';
  import router from '@/router';
  import ServiceReservation from '@/components/ServiceSelection/index.vue'; // 
  import UploadFile from '@/components/FileUpload/index.vue';
  import dayjs from 'dayjs'
  interface ServiceOrder {
    id?: number;
    demandPersonName: string;
    demandNo: string;
    demandPersonPhone: string;
    reservationTime: string;
    contactProvince: string;
    contactCity: string;
    contactCounty: string;
    contactAddress: string;
    serviceStatus: number;
  }
  
  export default defineComponent({
    components: {
      ServiceOrderForm,
      ServiceOrderDetail,
      AModal: Modal,
      AForm: Form,
      AFormItem: Form.Item,
      AInput: Input,
      AButton: Button,
      ServiceReservation,
      UploadFile
    },
    setup() {
      const serviceOrders = ref([]);
      const isFormVisible = ref(false);
      const isDetailVisible = ref(false);
      const isRefundFormVisible = ref(false);
      const selectedOrder = ref<ServiceOrder | null>(null);
      const isAddFormVisible = ref(false);
        const actionRef = ref();
        const productType = ref(1)
        const chargeType = ref(1)
        const isSmsStatusVisible = ref(false);
        const setActionRef = (ref) => {
            actionRef.value = ref;
        };
        const actionRefm = ref();

        const setActionRefm = (ref) => {
            actionRefm.value = ref;
        };

      const refundForm = ref({
        returnPrice: 0,
        returnRemark: '',
      });
      const handleUploadSuccess = (fileItem :any)=>{
        const response = fileItem.response;
        const url = response.data.url;
        // detailForm.value.fileList.push()
        // return response.data.url;
      }
      const pagination = ref({
        total: 0,
        current: 1,
        pageSize: 10,
      });
      const messageStatus = (record)=>{
        selectedOrder.value = record
        isSmsStatusVisible.value = true
        actionRefm.value.reload();
      }
      const columns = [
      { title: 'ID', dataIndex: 'id', hideInSearch: true ,width: 100},
      { title: 'CID', dataIndex: 'cid', ellipsis:true,width: 100 },
      { title: '预约时间', dataIndex: 'reservationTime', hideInSearch: true,ellipsis:true },
      { title: '开始时间', dataIndex: 'startDate', valueType:"dateRange" ,hideInTable: true},
      // { title: '结束时间', dataIndex: 'endDate', valueType:"date",hideInTable: true },
      { title : '服务项目',dataIndex: 'serviceProductName', hideInSearch: true,ellipsis:true},
      { title: '需求人姓名', dataIndex: 'demandPersonName',ellipsis:true },
      { title: '需求人手机号', dataIndex: 'demandPersonPhone',ellipsis:true },
      { title: '需求人座机号', dataIndex: 'demandPersonLandlinePhone', hideInSearch: true },
      { title: '需求人标签', dataIndex: 'demandPersonTag', hideInSearch: true },
      { title: '需求人省份', dataIndex: 'demandPersonProvince', hideInSearch: true },
      { title: '需求人城市', dataIndex: 'demandPersonCity', hideInSearch: true },
      { title: '需求人区县', dataIndex: 'demandPersonCounty', hideInSearch: true },
      { title: '需求人地址', dataIndex: 'demandPersonAddress', hideInSearch: true },
      { title: '分类名称', dataIndex: 'typeName', hideInSearch: true ,ellipsis:true},
      { title: '渠道名称', dataIndex: 'channelName', hideInSearch: true },
      { title: '四级分类名称', dataIndex: 'fourTypeName', hideInSearch: true,ellipsis:true },
      { title: '联系人姓名', dataIndex: 'contactName', hideInSearch: true,ellipsis:true },
      { title: '联系人手机号', dataIndex: 'contactPhone', hideInSearch: true ,ellipsis:true},
      { title: '服务地址省份', dataIndex: 'contactProvince',hideInSearch: true  },
      { title: '服务地址城市', dataIndex: 'contactCity' ,hideInSearch: true },
      { title: '服务地址区县', dataIndex: 'contactCounty' ,hideInSearch: true },
      { title: '服务地址', dataIndex: 'contactAddress',ellipsis:true },

      { title: '需求单编号', dataIndex: 'demandNo',ellipsis:true  },
      { title: '服务单号', dataIndex: 'serviceNo',ellipsis:true,hideInSearch: true  },
      { title: '金额', dataIndex: 'orderPrice', hideInSearch: true },
      { title: '退款金额', dataIndex: 'returnPrice', hideInSearch: true, },
      { title: '服务订单类型', dataIndex: 'productType', valueEnum:{
        1: { text: '保洁' },
        2: { text: '搬家' },
        3: { text: '保养' },
        4: { text: '维修' },
      } },
      { title: '服务订单状态', dataIndex: 'serviceStatus', hideInSearch: true, valueEnum:{
        '-1': { text: '已取消' },
        0: { text: '待付款' },
        1: { text: '已付款' },
      } },
      { title: '实收金额', dataIndex: 'payPrice', hideInSearch: true },
      { title: '支付时间', dataIndex: 'payTime', hideInSearch: true,ellipsis:true },
      { title: '服务订单创建时间', dataIndex: 'createTime', hideInSearch: true,ellipsis:true },
      { title: '服务订单创建人', dataIndex: 'createUserName', hideInSearch: true ,ellipsis:true},
      { title: '退款状态', dataIndex: 'returnStatus', hideInSearch: true,
        valueEnum:{
          '-1': { text: '已拒绝' },
          1: { text: '已提交' },
          2: { text: '已通过' },
        }
      },
      { title: '退款发起时间', dataIndex: 'returnLaunchTime', hideInSearch: true ,ellipsis:true},
      { title: '退款发起人', dataIndex: 'returnLaunchUserName', hideInSearch: true },
      { title: '操作', slotName: 'action', hideInSearch: true , fixed: 'right', width:550},
    ];


    const smsStatusColumns = [
    {
        title: '需求ID',
        dataIndex: 'demandId',
        key: 'demandId',
    },
    {
        title: '短信内容',
        dataIndex: 'content',
        key: 'content',
    },
    {
        title: '手机号',
        dataIndex: 'phone',
        key: 'phone',
    },
    {
        title: '发送时间',
        dataIndex: 'sendTime',
        key: 'sendTime',
    },
    {
        title: '接收时间',
        dataIndex: 'receiveDate',
        key: 'receiveDate',
    },
    {
        title: '发送状态',
        dataIndex: 'sendStatus',
        key: 'sendStatus',
        valueEnum:{
        1: { text: '等待回执' },
        2: { text: '发送失败' },
        3: { text: '发送成功' },
        4: { text: '未知状态' },
      }
    },
    {
        title: '发送流水号',
        dataIndex: 'bizId',
        key: 'bizId',
    },
    ];
      

    const serviceReservationData = ref({
      productType: 0,
      service: "",
      chargeType: 1,
      moveAddress: { province: "", provinceLabel: "", city: "", cityLabel: "", county: "", countyLabel: "" },
      enterAddress: "",
      contactName: "",
      contactPhone: "",
      address: { province: "", provinceLabel: "", city: "", cityLabel: "", county: "", countyLabel: "" },
      contactAddress: "",
      reservationTime: "",
      productList: [],
      
     
    });
    const serviceData = ref({
      fileList:[],
      requirementRecord: "",
    })
    const exportHandle = async (form) => {
      const params = form.value.model;
      const obj =  { ...params ,startDate: params.startDate? params.startDate[0]||'' : '', endDate:params.startDate? params.startDate[1]||'' : ''}
      const url  = new URLSearchParams(obj).toString();
      window.open('/service/demand/downloadServiceExcel?'+url)
    };

      const showAddForm = () => {
        selectedOrder.value = null;
        isFormVisible.value = true;
      };

      const handleAddSubmit = async () => {
        const id = selectedOrder?.value?.id
        await addServiceOrder({id,...serviceReservationData.value,...serviceData.value})
        
        console.log('submit')
      };
      const handleAdd = (record)=>{
        productType.value = record.productType
        chargeType.value = record.chargeType
        selectedOrder.value = record
        isAddFormVisible.value = true
      }
      const showEditForm = (order: ServiceOrder) => {
        selectedOrder.value = order;
        isFormVisible.value = true;
      };
  
      const hideForm = () => {
        isFormVisible.value = false;
      };
  
      const showDetail = async (order: ServiceOrder) => {
       const res = await getServiceOrderDetail(order.id);
       const deatil = await getProductDetail(order.id);
        selectedOrder.value = res.data;
        selectedOrder.value.deatil = deatil.data
        isDetailVisible.value = true;
      };
  
      const hideDetail = () => {
        isDetailVisible.value = false;
      };
      const handleEdit = (record: any) => {
      console.log('修改', record);
      router.push({
        name: 'DemandDetail',
        params: { id: record.id }
      });
    };
      const showRefundForm = (order: ServiceOrder) => {
        selectedOrder.value = order;
        refundForm.value = {
          returnPrice: 0,
          returnRemark: '',
        };
        isRefundFormVisible.value = true;
      };
  
      const hideRefundForm = () => {
        isRefundFormVisible.value = false;
      };
  
      const handleRefundSubmit = async () => {
        console.log(selectedOrder.value,'---selectedOrder')
        if (selectedOrder.value) {
          const responseData = await createRefund({
            demandId: selectedOrder.value.id,
            returnPrice: refundForm.value.returnPrice,
            returnRemark: refundForm.value.returnRemark,
          });
            Message.success('退款申请已提交');
            hideRefundForm();
            actionRef.value.reload();
        }
      };
  
      const confirmDelete = (order: ServiceOrder) => {
        Modal.confirm({
          title: '确认删除',
          content: '确定要删除此服务订单吗？',
          onOk: () => deleteOrder(order),
        });
      };
  
      const deleteOrder = async (order: ServiceOrder) => {
        await deleteServiceOrder( order.id);
        actionRef.value.reload();
      };
  
      const handleSubmit = () => {
        hideForm();
        actionRef.value.reload();
      };
  
      const handlePageChange = (page: number) => {
        pagination.value.current = page;
        actionRef.value.reload();
      };
      const cancel = async (record) => {
        const responseData = await createRefund({
            demandId: record.id,
          });
          Message.success('取消申请已提交');
      };
  
      return {
        serviceOrders,
        columns,
        isFormVisible,
        isDetailVisible,
        isRefundFormVisible,
        selectedOrder,
        refundForm,
        pagination,
        showAddForm,
        showEditForm,
        hideForm,
        showDetail,
        hideDetail,
        showRefundForm,
        hideRefundForm,
        handleRefundSubmit,
        confirmDelete,
        handleSubmit,
        handlePageChange,
        getServiceOrders,
        setActionRef,
        handleEdit,
        isAddFormVisible,
        serviceReservationData,
        handleAddSubmit,
        handleAdd,
        handleUploadSuccess,
        serviceData,
        exportHandle,
        dayjs,
        cancel,
        productType,
        chargeType,
        isSmsStatusVisible,
        messageStatus,
        getSmsStatusList,
        setActionRefm,
        smsStatusColumns
      };
    },
  });
  </script>